/*
 * Copyright (c) 2017. AnStudio + Medical Plus Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.anstudio.app.lhasa.common.secure;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import static com.anstudio.app.lhasa.common.consts.Constants.EMPTY_STRING;
import static com.anstudio.app.lhasa.common.consts.Constants.MD5_ALGORITHM_MD5;

public class MD5Utils {

    public static String toSequentialMD5(String...list) {
        String ret = EMPTY_STRING;
        for (String item : list) {
            ret += toMD5(item);
        }

        return ret;
    }

    public static String toSequentialMD5(List<String> list) {
        String ret = EMPTY_STRING;
        for (String item : list) {
            ret += toMD5(item);
        }

        return ret;
    }

    public static String toMD5(String str) {
        return toMd5(str, MD5_ALGORITHM_MD5, EMPTY_STRING);
    }

    public static String toMd5(String original, String encrypted, String separator) {
        try {
            String result;
            byte[] bytes = original.getBytes();
            MessageDigest algorithm = MessageDigest.getInstance(encrypted);
            algorithm.reset();
            algorithm.update(bytes);
            result = toHexString(algorithm.digest(), separator);
            return result;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toHexString(byte[] bytes, String separator) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", 0xFF & b)).append(separator);
        }
        return hexString.toString();
    }

    /**
     * Calculate MD5 sum of a file
     */
    static final public String calcMD5(File file) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            FileInputStream input = new FileInputStream(file);
            byte[] buf = new byte[1024];

            while (input.available() > 0) {
                int res = input.read(buf, 0, buf.length);

                md.update(buf, 0, res);
            }
            input.close();

            byte[] md5 = md.digest();

            return bytesToHexString(md5);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "" + file.length();
    }

    /**
     * Convert an array of bytes to a string of hexadecimal numbers
     */
    static final private String bytesToHexString(byte[] array) {
        StringBuffer res = new StringBuffer();

        for (int i = 0; i < array.length; i++) {
            int val = array[i] + 256;
            String b = "00" + Integer.toHexString(val);
            int len = b.length();
            String sub = b.substring(len - 2);

            res.append(sub);
        }

        return res.toString();
    }
}
